package controller;

import action.MyInterceptor;
import action.UserInterceptor;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import model.User;
import result.CodeMsg;
import result.Result;
import service.KnowledgeService;
import util.UploadUtil;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.*;


public class KnowledgeController extends Controller {


    KnowledgeService knowledgeService = KnowledgeService.knowledgeService;

    public void index() {
        render("/login/index.html");
    }

    public  void normalSearch(){
        render("/normalUser/normalUserSearch.html");
    }


    public void userJudge(){
        Record user=getSessionAttr("user");
        String userType=user.get("user_type");
        System.out.println(userType);
        if ("管理员".equals(userType)){
            render("/knowledge/searchResult.html");
        }else if ("普通用户".equals(userType)){
            render("/normalUser/normalUserSearch.html");
        }else{
            index();
        }
    }

    @Before(MyInterceptor.class)
    public  void tcm(){render("/knowledge/searchResult.html");}


    @Before(MyInterceptor.class)
    public  void addTcm(){
        render("/knowledge/add.html");
    }
    @Before(MyInterceptor.class)
    public  void searchTcm(){
        render("/knowledge/searchResult.html");
    }

    public void name(){
       Record record = getSessionAttr("user");
       String username=record.get("username");
       renderJson(username);

    }

    public void login() {
        String username = getPara("username");
        String password = getPara("password");
        Result flag = knowledgeService.login(username,password);
        Record record = (Record) flag.getData();
        setSessionAttr("user",record);
        renderJson(flag);
    }


    //查询所有(实现分页)
//    @Before(MyInterceptor.class)
    public void selectAll() {
        int limit = getParaToInt("limit");
        int page = getParaToInt("page");
        List<Record> record = knowledgeService.selectAll(limit, page);
        int count = knowledgeService.countRecord();
        renderJson(Result.layui(count, record));
    }

    //查询(by  holderName)
    @Before(MyInterceptor.class)
    public void selectByName() throws UnsupportedEncodingException {
        String holderName = getPara("holderName");
        List<Record> list = knowledgeService.selectByName(holderName);
        Integer count = list.size();
        renderJson(Result.layui(count, list));
    }

    //查询(by projectName)
    public void selectByProjectName() {
        String projectName = getPara("projectName");
        List<Record> list = knowledgeService.selectByProjectName(projectName);
        Integer count = list.size();
        renderJson(Result.layui(count, list));
    }


    //详情
    public void selectDetail() {
        Integer id = getParaToInt("id");
        List<Record> list = knowledgeService.selectDetail(id);
        Integer count = list.size();
        renderJson(Result.layui(count, list));
    }

    public void ueditorUpload(){
        // 百度编辑器加载出按钮图标前 会将所有控件的路径 先通过config.json
        // 文件加载出来(包括上传图片路径，视频路径等路径都是通过config.json 文件读取的)
        // 所以某些控件点击不了 是因为 config.json文件没有找到 或者是文件里面的路径有问题
        if ("config".equals(getPara("action"))) {
            // 这里千万注意 "config.json" 文件前方的目录一定要正确
            render("/assets/ueditor-1.4.3.3/jsp/config.json");//这里地址写成自己的config.json所在的地址
            return;
        }
        // "upfile" 来自 config.json 中的 imageFieldName 配置项
        UploadFile uf = getFile("upfile");
        String fileName = uf.getFileName();
        File source=  uf.getFile();
        Map<String,String> map = UploadUtil.renameFile(uf.getUploadPath(),fileName);
        source.renameTo(new File( map.get("path")));
        String[] typeArr = fileName.split("\\.");
        Ret ret = Ret.create("state", "SUCCESS")
                .set("url", map.get("name"))//文件上传地址
                .set("title", fileName)
                .set("original", uf.getOriginalFileName())
                .set("type", "." +typeArr[typeArr.length-1]) // 这里根据实际扩展名去写
                .set("size", uf.getFile().length());
        renderJson(ret);

    }


    //插入
    @Before(UserInterceptor.class)
    public void insertRecord() {

        String holderName = getPara("holderName");
        System.out.println("holderName:"+holderName);
        String holderType = getPara("holderType");
        System.out.println("type:"+holderType);
        String sex = "";
        String birth = "";
        String nationality = "";
        if (holderType.equals("个人")){
            sex = getPara("sex");
            birth = getPara("birth");
            nationality = getPara("nationality");
        }
        System.out.println("人类型"+holderType);
        String medicType = getPara("medicType");
        String postaddress = getPara("postaddress");
        String phone = getPara("phone");
        String email = getPara("email");
        String postalcode = getPara("postalCode");
        String projectName = getPara("projectName");
        String area = getPara("area");
        String holderIntroduction = getPara("holderIntroduction");
        String inheritTime = getPara("inheritTime");
        Integer inheritTimes = getParaToInt("inheritTimes");
        String inheritCondition = getPara("inheritCondition");
        String contentDescription = getPara("contentDescription");
        String mainCharacter = getPara("mainCharacter");
        String importantCharacter = getPara("importantCharacter");
        System.out.println("medicType"+medicType);

        String document = getPara("document");
        Boolean b = knowledgeService.insertRecord(holderName,holderType, sex, birth, nationality, postaddress, phone, email, postalcode, projectName, area, holderIntroduction, inheritTime, inheritTimes, inheritCondition, medicType, contentDescription, mainCharacter, importantCharacter, document);
        System.out.println("插入结果:" + b);
        if (b) {
            renderJson(Result.success(CodeMsg.SUCCESS));
        } else {
            renderJson(Result.error(CodeMsg.INSERT_ERROR));
        }
    }


    //修改
    @Before(UserInterceptor.class)
    public void updateRecord() {
        Integer id = getParaToInt("id");
        String holderName = getPara("holderName");
        System.out.println("holderName:"+holderName);
        String holderType = getPara("holderType");

        System.out.println("type:"+holderType);
        String sex = "";
        String birth = "";
        String nationality = "";
        if (holderType.equals("个人")){
            sex = getPara("sex");
            birth = getPara("birth");
            nationality = getPara("nationality");
        }
        System.out.println("人类型"+holderType);
        String medicType = getPara("medicType");
        String postaddress = getPara("postaddress");
        String phone = getPara("phone");
        String email = getPara("email");
        String postalcode = getPara("postalCode");
        String projectName = getPara("projectName");
        String area = getPara("area");
        String holderIntroduction = getPara("holderIntroduction");
        String inheritTime = getPara("inheritTime");
        Integer inheritTimes = getParaToInt("inheritTimes");
        String inheritCondition = getPara("inheritCondition");
        String contentDescription = getPara("contentDescription");
        String mainCharacter = getPara("mainCharacter");
        String importantCharacter = getPara("importantCharacter");
        System.out.println("medicType"+medicType);

        Boolean b = knowledgeService.updateRecord(id,holderName,sex,birth,nationality,postaddress,phone,email,postalcode,projectName,area,holderIntroduction,inheritTime,inheritTimes,inheritCondition,medicType,contentDescription,mainCharacter,importantCharacter);
        if (b) {
            renderJson(Result.success(CodeMsg.SUCCESS));
        } else {
            renderJson(Result.error(CodeMsg.UPDATE_ERROR));
        }
    }


    //删除
    @Before(UserInterceptor.class)
    public void deleteById() {
        String[] id = getParaValues("id[]");

        System.out.println(id.toString());
        StringBuffer sb = new StringBuffer("(");
        for (String str : id) {
            sb.append(str).append(",");
        }
        Integer length = sb.length();
        sb.setCharAt(length - 1, ')');
        String idStr = sb.toString();
        System.out.println("要删除的id序列 " + idStr);
        Integer deleteTotal = knowledgeService.deleteById(idStr);

        if ( deleteTotal > 0) {
            renderJson(Result.success(CodeMsg.SUCCESS));
        } else {
            renderJson(Result.error(CodeMsg.DELETE_ERROR));
        }
    }


    public void  logOut(){
        setSessionAttr("user",null);
        index();
    }


}
